<template>
	<div class="login_box">
		<div class="logo"></div>
		<div class="content">
			<h3>登录后即可打卡/购买食材</h3>
			<p>未注册的手机号码则会自动注册并登录</p>
			<h1>{{ defaultTel | tel }}</h1>
			<van-field
				v-model="verificationCode"
				center
				clearable
				label="短信验证码"
				placeholder="请输入短信验证码"
				style="margin-bottom: 20px"
				maxlength="6"
			>
				<template #button>
					<van-button size="small" type="primary" @click="sendVerificationCode" :disabled="btnStatus">{{
						btnText
					}}</van-button>
				</template>
			</van-field>
			<!-- 用户协议 -->
			<van-checkbox v-model="agreement" label-disabled>
				已经阅读并同意 <a href="javascript:;">《用户协议》</a>
			</van-checkbox>
		</div>
	</div>
</template>

<script>
import { login } from '@/api/user';
export default {
	name: 'UserLoginIndex',
	watch: {
		async verificationCode(code) {
			if (code.length !== 6) return;
			if (!this.agreement) return this.toast('请先同意用户协议');

			const LoginResult = await login({ tel: this.defaultTel, code: this.verificationCode });
			if (LoginResult.data.status == -1) {
				this.verificationCode = '';
				this.$toast('验证码输入错误，请重新尝试……');
				this.readonly = true;
				setTimeout(() => {
					this.readonly = false;
				}, 2000);
			} else if (LoginResult.data.token) {
				this.$toast('登录成功，正在跳转……');
				this.$store.dispatch('userLogin', LoginResult.data);
				setTimeout(() => {
					// this.$router.push('/');
					if (sessionStorage.getItem('loginPath')) {
						this.$router.push(sessionStorage.getItem('loginPath'));
					} else {
						this.$router.push('/');
					}
				}, 1000);
			}
		},
	},
	filters: {
		// 格式化时间
		tel(tel) {
			// 手机号码星星隐藏
			return tel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		},
	},
	data() {
		return {
			defaultTel: '18888888888',
			verificationCode: '',
			agreement: true,
			btnStatus: false,
			btnText: '发送验证码',
		};
	},
	methods: {
		/** @method 发送验证码 */
		sendVerificationCode() {
			this.$toast('验证码发送成功，验证码为【123456】');
			this.btnStatus = true;
			let sum = 10;
			let timeInterval = setInterval(() => {
				this.btnText = `${--sum}s后重新发送`;
				if (sum == 0) {
					clearInterval(timeInterval);
					this.btnText = '重新发送';
					this.btnStatus = false;
				}
			}, 1000);
		},
	},
};
</script>

<style scoped>
h1,
h3 {
	padding: 30px;
}

.login_box {
	width: 100%;
	height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	text-align: center;
	background: url('@/assets/images/login-bg.png') no-repeat;
}

.login_box .logo {
	width: 100px;
	height: 100px;
	background: url('@/assets/images/logo.png') no-repeat;
	background-size: 100%;
	margin-bottom: 20px;
}

.content {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
</style>
